package com.wandian.cqcsk.application;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Log;

import androidx.annotation.RequiresApi;
import androidx.multidex.MultiDex;

import com.bytedance.sdk.openadsdk.activity.base.TTRewardExpressVideoActivity;
import com.bytedance.sdk.openadsdk.activity.base.TTRewardVideoActivity;
import com.component.dly.xzzq_ywsdk.YwSDK;
import com.duoyou.task.openapi.DyAdApi;
import com.iBookStar.views.YmConfig;
import com.ledong.lib.leto.Leto;
import com.ledong.lib.leto.main.LetoActivity;
import com.ledong.lib.leto.main.LetoActivityL;
import com.ledong.lib.leto.main.WebViewActivity;
import com.mgc.leto.game.base.LetoCore;
import com.mgc.leto.game.base.main.LetoRewardedVideoActivityL;
import com.mylib.libcore.AppContext;
import com.mylib.libcore.bean.EveryDayCoin;
import com.mylib.libcore.tools.MiitHelper;
import com.mylib.libcore.tools.TTAdManagerHolder;
import com.mylib.libcore.utils.ScreenUtil;
import com.mylib.libcore.utils.UIUtils;
import com.qq.e.ads.LandscapeADActivity;
import com.qq.e.ads.RewardvideoLandscapeADActivity;
import com.qq.e.comm.managers.GDTADManager;
import com.tencent.smtt.sdk.WebView;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;
import com.wandian.cqcsk.tools.ActivitySelfManager;
import com.wandian.cqcsk.tools.YLInItTools;
import com.xianwan.sdklibrary.helper.XWAdSdk;


import org.litepal.LitePalApplication;

import me.jessyan.autosize.AutoSizeConfig;

import static com.mylib.libcore.config.AppConfig.DUOYOU_APP_ID;
import static com.mylib.libcore.config.AppConfig.DUOYOU_AppSecret;
import static com.mylib.libcore.config.AppConfig.GDT_APP_ID;
import static com.mylib.libcore.config.AppConfig.XIANWANG_AppSecret;
import static com.mylib.libcore.config.AppConfig.XIANWAN_APP_ID;
import static com.mylib.libcore.config.AppConfig.XIAOYOUXI_APP_ID;
import static com.mylib.libcore.config.AppConfig.YOUMENG_APP_KEY;
import static com.mylib.libcore.config.AppConfig.YOUMENG_Message_Secret;
import static com.mylib.libcore.config.AppConfig.YUEMENG_APP_ID;
import static com.mylib.libcore.config.AppConfig.YWHZ_APP_ID;
import static com.mylib.libcore.config.AppConfig.YWHZ_AppSecret;
import static com.mylib.libcore.config.AppSPKeyConfig.APP_CHANNEL;
import static com.mylib.libcore.config.AppSPKeyConfig.APP_OA_ID;


public class BaseApplication extends LitePalApplication {
    private int sys_width = 360;
    private static BaseApplication instance = null;

    public static synchronized BaseApplication getInstance() {
        return instance;
    }
    private String channel="";
    @Override
    public void onCreate() {
        super.onCreate();
         instance = this;
        //webview-androidp多进程异常处理
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P)webviewSetPath(this);
         AppContext.getInstance().init(this);
        try {
            sys_width = ScreenUtil.getScreenWidth(this);
            AppContext.getInstance().getAppPreferenceForever().setAppSysWidth(UIUtils.px2dp(sys_width));
        } catch (Exception e) { }

        //监听屏幕生命周期
        AppContext.getInstance().getAppPreferencesHelper().setAppStartTime();
        registerActivityLifecycleCallbacks(new ActivitySelfManager());
        //渠道包初始化
        channel = AppContext.getInstance().getAppPreferencesHelper().getKeyValue(APP_CHANNEL);
        if(UIUtils.isEmpty(channel))getChannelName(this);
         // 穿山甲SDK初始化
        TTAdManagerHolder.init(this);
        //广点通
        GDTADManager.getInstance().initWith(this, GDT_APP_ID);
         //闲玩
         XWAdSdk.init(this, XIANWAN_APP_ID, XIANWANG_AppSecret); //初始化 参数
        //广告阅盟
        YmConfig.initNovel(this,YUEMENG_APP_ID);//初始化 SDK
        //鱼玩盒子
        YwSDK.Companion.init(this,YWHZ_AppSecret,YWHZ_APP_ID,AppContext.getInstance().getAppPreferencesHelper().getKeyValue("user_id"),"");
        //多游
        DyAdApi.getDyAdApi().init(getContext(), DUOYOU_APP_ID, DUOYOU_AppSecret,"", true);
        //小游戏
        try {
            //小游戏Sdk初始化-SDK带渠道ID初始化
            LetoCore.setSkipWebViewDataDirectorySuffixSetting(true);
            Leto.init(getApplicationContext(),XIAOYOUXI_APP_ID);
            AutoSizeConfig.getInstance().getExternalAdaptManager()
                    .addCancelAdaptOfActivity(LetoActivity.class)
                    .addCancelAdaptOfActivity(LetoActivityL.class)
                    .addCancelAdaptOfActivity(WebViewActivity.class)
                    .addCancelAdaptOfActivity(RewardvideoLandscapeADActivity.class)
                    .addCancelAdaptOfActivity(LetoRewardedVideoActivityL.class)
                    .addCancelAdaptOfActivity(LandscapeADActivity.class)
                    .addCancelAdaptOfActivity(TTRewardExpressVideoActivity.class)
                    .addCancelAdaptOfActivity(TTRewardVideoActivity.class);
        }catch (Exception e){}
        //友盟
        initUMPush();
        //开启LitePal 数据存储
        LitePalApplication.initialize(this);
        //获取OAID等设备标识符
        initOAID(this);
    }


    /**
     * 初始话OA_ID
     * @param application
     */
    private void initOAID(Application application){
        try {
            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                MiitHelper miitHelper=  new MiitHelper(new MiitHelper.AppIdsUpdater() {
                    @Override
                    public void OnIdsAvalid(String oaid, String vaid, String aaid) {
                        AppContext.getInstance().getAppPreferenceForever().SetAppOAID(oaid);
                        Log.d("getDeviceIds","oaId="+oaid);
                        //一览云
                        YLInItTools.initYLByOaid(application,oaid,vaid,aaid);
                    }

                    @Override
                    public void getIdError() {
                        Log.d("getDeviceIds","oaId=error");
                        AppContext.getInstance().getAppPreferenceForever().SetAppOAID("");
                        //一览云
                        YLInItTools.initYLNOOaid(application);
                    }
                });
                miitHelper.getDeviceIds(getApplicationContext());
            }else {
                Log.d("getDeviceIds","oaId=no");
                AppContext.getInstance().getAppPreferenceForever().SetAppOAID("");
                //一览云
                YLInItTools.initYLNOOaid(application);
            }
        }catch (Exception e){
            AppContext.getInstance().getAppPreferenceForever().SetAppOAID("");
            YLInItTools.initYLNOOaid(application);
        }
    }

    @RequiresApi(api = 28)
    public void webviewSetPath(Context context) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                String processName = getProcessName(context);
                if (!getApplicationContext().getPackageName().equals(processName)) {//判断不等于默认进程名称
                    WebView.setDataDirectorySuffix(processName);
                }
            }
        }catch (Exception e){}

    }

    public String getProcessName(Context context) {
        if (context == null) return null;
        try {
            ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            for (ActivityManager.RunningAppProcessInfo processInfo : manager.getRunningAppProcesses()) {
                if (processInfo.pid == android.os.Process.myPid()) {
                    return processInfo.processName;
                }
            }
            return null;
        } catch (Exception e){return null;}
    }



    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        //因为引用的包过多，实现多包问题
        MultiDex.install(this);
    }

    /**
     * 获取渠道名
     * @param context 此处习惯性的设置为activity，实际上context就可以
     * @return 如果没有获取成功，那么返回值为空
     */
    private  String getChannelName(Context context) {
        if (context == null) return null;
        String channelName = null;
        try {
            PackageManager packageManager = context.getPackageManager();
            if (packageManager != null) {
                //注意此处为ApplicationInfo 而不是 ActivityInfo,因为友盟设置的meta-data是在application标签中，而不是某activity标签中，所以用ApplicationInfo
                ApplicationInfo applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
                if (applicationInfo != null) {
                    if (applicationInfo.metaData != null) {
                        channelName = String.valueOf(applicationInfo.metaData.get("UMENG_CHANNEL"));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(channelName!=null ){
            channel = channelName;
        }else {
            channel = "";
        }
        AppContext.getInstance().getAppPreferencesHelper().setKeyValue(APP_CHANNEL,channel);
        return channelName;
    }

    /**
     * 友盟初始化
     */
    private void initUMPush(){
        // 在此处调用基础组件包提供的初始化函数 相应信息可在应用管理 -> 应用信息 中找到 http://message.umeng.com/list/apps
        // 参数一：当前上下文context；
        // 参数二：应用申请的Appkey（需替换）；
        // 参数三：渠道名称；
        // 参数四：设备类型，必须参数，传参数为UMConfigure.DEVICE_TYPE_PHONE则表示手机；传参数为UMConfigure.DEVICE_TYPE_BOX则表示盒子；默认为手机；
        // 参数五：Push推送业务的secret 填充Umeng Message Secret对应信息（需替换）
        UMConfigure.init(this, YOUMENG_APP_KEY, channel, UMConfigure.DEVICE_TYPE_PHONE, YOUMENG_Message_Secret);

        //获取消息推送代理示例
        PushAgent mPushAgent = PushAgent.getInstance(this);
//        mPushAgent.setNotificationPlaySound(MsgConstant.NOTIFICATION_PLAY_SERVER); //服务端控制声音
        //注册推送服务，每次调用register方法都会回调该接口
        mPushAgent.register(new IUmengRegisterCallback() {

            @Override
            public void onSuccess(String deviceToken) {
                //注册成功会返回deviceToken deviceToken是推送消息的唯一标志
                System.out.println("youmeng_state"+"注册成功：deviceToken：-------->  " + deviceToken);

            }

            @Override
            public void onFailure(String s, String s1) {
                System.out.println("youmeng_state"+"注册失败：-------->  " + "s:" + s + ",s1:" + s1);

            }
        });

    }


}
